//
//  PasteController.swift
//  HisPaste
//
//  Created by 烟雀 on 2024/2/14.
//

import Foundation
import Cocoa

struct SystemPaste{
    
    static private let _pasteboard = NSPasteboard.general
    
    static func curPasteData() -> String?{
        return _pasteboard.string(forType: .string)
    }
    
    static func writeToPaste(data: String){
//        SystemPaste.stopCheckChange()
        
        _pasteboard.clearContents()
        _pasteboard.setString(data, forType: .string)
        
        // 自己的操作, 不需要触发,
        // 去掉, 需要触发替换时候
        // _lastPasteCount += 1
        
//        SystemPaste.restartCheckChange()
    }
    
    static private let _didChangePaste = Emitter<String>()
    static let didChangePasteEvent = _didChangePaste.event()
    
    static private var _lastPasteCount = _pasteboard.changeCount
    static private var _stopCheckChangeEvent = false
    static func stopCheckChange(){
        _stopCheckChangeEvent = true
    }
//    static func restartCheckChange(){
//        if _stopCheckChangeEvent{
//            _stopCheckChangeEvent = false
//            _lastPasteCount = _pasteboard.changeCount
//            SystemPaste.checkPasteChange()
//        }
//    }
    static func checkPasteChange(timer: Int=1){
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(timer), execute: {
            let curCount = _pasteboard.changeCount
            if curCount != _lastPasteCount{
                // 说明剪切板变化
                AppLog.debug("系统剪贴板变化")
                _lastPasteCount = curCount
                self._didChangePaste.fire(args: curPasteData())
            }
            
            // 一直循环 只要没有 stopCheckChangeEvent
            if !_stopCheckChangeEvent{checkPasteChange()}
        })
    }
    
}



